use actix_web::{App, HttpServer};
use config::ConfigManager;
use log::info;
use std::error::Error;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {

    // init logger
    attestation_common::log::init().expect("Failed to initialize logger");

    info!("Remote Attestation Client starting");
    
    // Use command line arguments if provided
    let args: Vec<String> = std::env::args().collect();
    let config_path = if args.len() > 1 { &args[1] } else { "" };

    info!("Starting to load configuration file");
    let config_manager: Arc<ConfigManager> = Arc::new(ConfigManager::new(config_path).await?);
    info!("Configuration file loaded successfully: {}", config_manager.get_config_path());

    // Get configuration object
    let config = config_manager.get_config().await;

    // Print working directory and some basic information
    info!("Current working directory: {:?}", std::env::current_dir()?);

    /*
        todo:
        1. Load plugins
        2. Load startup remote attestation challenge tasks and scheduled tasks
        3. Start listening, providing RESTful API
    */

    // start server
    info!("Starting server at listen address: {}:{}", config.agent.listen_address, config.agent.listen_port);
    Ok(HttpServer::new(move || {
        App::new()
    })
    .bind(format!("{}:{}", config.agent.listen_address, config.agent.listen_port))?
    .run()
    .await?)
}
